﻿@model AMAP.Areas.Admin.Models.Basket.AdminBasketCreateViewModel
@{
    ViewBag.Title = "Création du panier de la semaine";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@{
    int i = 0, j = 0, k = 0;
}

@section Javascript {
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.globalize/globalize.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.globalize/cultures/globalize.culture.fr-FR.js")" type="text/javascript"></script>
    <script type="text/javascript">
        $.validator.methods.number = function (value, element) {
            if (Globalize.parseFloat(value))
                return true;
            return false;
        }
        Globalize.culture('fr-FR');


        var NbrBasket;
        var CurrentBasket;
        var BasketPrice = 0;
        $(function () {
            NbrBasket = $('#NumberOfBasket').val();
            CurrentBasket = $('#CurrentBasket');
            $('.stock input[type="text"].use').each(function () {
                $(this).blur(function () {
                    $(this).val($(this).val().replace(".", ","));
                    computeBasket();
                });
            });
            $('.offer input[type="text"].use').each(function () {
                $(this).blur(function () {
                    $(this).val($(this).val().replace(".", ","));
                    computeBasket();
                    refreshQuantityToOrder(this);
                });
            });
            $('.external input[type="text"].use').each(function () {
                $(this).blur(function () {
                    $(this).val($(this).val().replace(".", ","));
                    computeBasket();
                    refreshQuantityToOrder(this);
                });
            });
            $(document).scroll(function () {
                var ScrollHeight = parseInt($(document).scrollTop());
                if (ScrollHeight < 111) {
                    $('.fixed-opacity').css("margin-top", (111 - ScrollHeight) + 'px');
                }
                else {
                    $('.fixed-opacity').css("margin-top", '0px');
                }
            });
        });

        function computeBasket() {
            CurrentBasket.empty();
            BasketPrice = 0;
            $('.stock input.use').each(function () {
                if (parseFloat($(this).val().replace(",", ".")) > 0) {
                    var NbrByBasket = parseFloat($(this).val().replace(",", ".")) / NbrBasket;
                    CurrentBasket.append($("<li>" + (NbrByBasket + "").replace(".", ",") + " " + getBrotherContent(this, 2) + " de " + getBrotherContent(this, 0) + "</li>"));
                    BasketPrice += NbrByBasket * parseFloat(getBrotherContent(this, 1).replace(" €", "").replace(",", "."), 10);
                } else
                    $(this).val('');
            });
            $('.offer input.use').each(function () {
                if (parseFloat($(this).val().replace(",", ".")) > 0) {
                    var NbrByBasket = parseFloat($(this).val().replace(",", "."));
                    CurrentBasket.append($("<li>" + (NbrByBasket + "").replace(".", ",") + " " + getBrotherContent(this, 2) + " de " + getBrotherContent(this, 0) + "</li>"));
                    BasketPrice += NbrByBasket * parseFloat(getBrotherContent(this, 1).replace(" €", "").replace(",", "."), 10);
                } else
                    $(this).val('');
            });
            $('.external input.use').each(function () {
                if (parseFloat($(this).val().replace(",", ".")) > 0) {
                    var NbrByBasket = parseFloat($(this).val().replace(",", "."));
                    CurrentBasket.append($("<li>" + (NbrByBasket + "").replace(".", ",") + " " + getBrotherContent(this, 2) + " de " + getBrotherContent(this, 0) + "</li>"));
                    BasketPrice += NbrByBasket * parseFloat(getBrotherContent(this, 1).replace(" €", "").replace(",", "."), 10);
                } else
                    $(this).val('');
            });

            $("#CurrentBasketPrice").get(0).innerHTML = BasketPrice.toFixed(2).replace(".", ",");
            $("#BasketPrice").val(BasketPrice.toFixed(2).replace(".", ","));
        }

        function getBrotherContent(element, rank) {
            return element.parentNode.parentNode.getElementsByTagName("td")[rank].innerHTML;
        }

        function refreshQuantityToOrder(element) {
            if (parseFloat($(element).val().replace(",", ".")) > 0)
                $(element.parentNode.parentNode.getElementsByTagName("input")[1]).val((NbrBasket * parseFloat($(element).val().replace(",", ".")) + "").replace(".", ","));
        }

    </script>
}
<h2>Créer un panier</h2>
@if (Model.NumberOfBasket > 0)
{
    using (Html.BeginForm())
    { 

    <p>Il est nécessaire de composer <strong>@Model.NumberOfBasket @(Model.NumberOfBasket > 0 ? "paniers" : "panier")</strong> pour la semaine prochaine.</p>
    <input type="hidden" id="NumberOfBasket" value="@Model.NumberOfBasket" />
    
    <div class="fixed-opacity ">
        <a onclick="if(this.innerHTML=='Afficher') {this.parentNode.className += 'permanent';this.innerHTML='Masquer';} else {this.parentNode.className = this.parentNode.className.replace('permanent', '');this.innerHTML='Afficher';}">Afficher</a>
        <p style="margin-bottom:10px">Composition actuelle du panier :</p>
        <ul id="CurrentBasket" style="list-style: none;overflow: auto; max-height:145px;margin:0;">
            <li>Vide</li>
        </ul>
        <p style="margin:10px 0">
            Coût de revient du panier : <span id="CurrentBasketPrice">0,00</span> €
        </p>
    </div>

        if (Model.Stock.Count > 0)
        { 
    <h3 style="margin-top:61px;">Utiliser les stocks</h3>
    <table class="bsk stock">
        <thead>
            <tr>
                <th class="Name">Nom du produit</th>
                <th class="Price">Prix d'achat</th>
                <th class="Unit">Unité</th>
                <th class="Expiration">Date de péremption</th>
                <th class="Quantity">Stock</th>
                <th class="OQuantity">Quantité à utiliser</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.Stock)
            {
                <tr>
                    <td>@item.Name</td>
                    <td>@item.Price.ToEuro()</td>
                    <td>@item.Unit</td>
                    <td>
                        @{
                DateTime ExpirationDate = item.ExpirationDate;
                int NbrDay = (int)(ExpirationDate - DateTime.Now).TotalDays;
                        }
                        @ExpirationDate.ToShortDateString() - @NbrDay @(NbrDay > 1 ? "jours" : "jour")
                    </td>
                    <td>@item.Quantity</td>
                    <td class="center">
                        <input type="text" name="StockUsage[@i].Quantity" id="StockUsage[@i].Quantity" placeholder="Quantité à utiliser" class="use" />
                        <input type="hidden" value="@item.Id" name="StockUsage[@i].StockId" id="StockUsage[@i].StockId" />
                        <input type="hidden" value="@item.Type" name="StockUsage[@i].Type" id="StockUsage[@i].Type" />
                        @{i++;}
                    </td>
                </tr>
            }
        </tbody>
    </table>
        }
        else
        { 
    <p>Aucun stock</p>
        }

        if (Model.NewOffers.Count > 0)
        { 
    <h3>Commander aux fournisseurs</h3>
    <table class="bsk offer">
        <thead>
            <tr>
                <th class="Name">Nom du produit</th>
                <th class="Price">Prix</th>
                <th class="Unit">Unité</th>
                <th class="Expiration">Date de péremption</th>
                <th class="Quantity">Quantité</th>
                <th class="OUnit">Unité / panier</th>
                <th class="OQuantity">Quantité à commander</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.NewOffers)
            {
                <tr>
                    <td>@item.Product.Name</td>
                    <td>@item.Price.ToEuro()</td>
                    <td>@item.Unit</td>
                    <td>
                        @{
                DateTime ExpirationDate = item.HarvestDate.AddDays(item.Product.ShelfLife);
                int NbrDay = (int)(ExpirationDate - DateTime.Now).TotalDays;
                        }
                        @ExpirationDate.ToShortDateString() (@NbrDay @(NbrDay > 1 ? "jours" : "jour"))
                    </td>
                    <td>@item.Quantity</td>
                    <td class="center">
                        <input type="text" name="OfferUsage[@j].Unit" placeholder="Nombre par panier" class="use" style="max-width:135px;" />
                    </td>
                    <td class="center">
                        <input type="text" name="OfferUsage[@j].Quantity" placeholder="Quantité à commander" />
                        <input type="hidden" value="@item.Id" name="OfferUsage[@j].OfferId" />
                        @{j++;}
                    </td>
                </tr>
            }
        </tbody>
    </table>
        }
        else
        {
    <p>Aucune proposition des fournisseurs</p>
        }
        if (Model.ExternalOffers.Count > 0)
        { 
    <h3>Commander aux autres AMAP</h3>
    <table class="bsk external">
        <thead>
            <tr>
                <th class="Name">Nom du produit</th>
                <th class="Price">Prix</th>
                <th class="Unit">Unité</th>
                <th class="Quantity">Quantité</th>
                <th class="OUnit">Unité / panier</th>
                <th class="OQuantity">Quantité à commander</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.ExternalOffers)
            {
                <tr>
                    <td>@item.Name</td>
                    <td>@item.Price.ToEuro()</td>
                    <td>@item.Unit</td>
                    <td>@item.Quantity</td>
                    <td class="center">
                        <input type="text" name="ExternalUsage[@k].Unit" placeholder="Nombre par panier" class="use" style="max-width:135px;" />
                    </td>
                    <td class="center">
                        <input type="text" name="ExternalUsage[@k].Quantity" placeholder="Quantité à commander" />
                        <input type="hidden" value="@item.AmapId" name="ExternalUsage[@k].AmapId" />
                        <input type="hidden" value="@item.OfferId" name="ExternalUsage[@k].OfferId" />
                        @{k++;}
                    </td>
                </tr>
            }
        </tbody>
    </table>
        }
        else
        { 
    <p>Aucune proposition récupérée dans les autres AMAP</p>
        }
        
    <div class="editor-label">
        @Html.LabelFor(m => m.BasketPrice)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(m => m.BasketPrice, new { onblur = "this.value = this.value.replace('.',',');", placeholder = "Prix du panier" })
        @Html.ValidationMessageFor(m => m.BasketPrice)
    </div>
    <p>L'enregistrement de ce panier mettra automatiquement à jour les stocks et déclenchera les commandes aux fournisseurs et autres AMAP.</p>
    <input type="submit" value="Enregistrer la composition" />
    }
}
else
{ 
    <p>Il n'y a actuellement aucune commande pour la semaine prochaine.</p>
}